package com.ruoyi.goods.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.goods.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;


/**
 * @Author {那蓝桉}
 * @Date: 2023/08/16/ 10:49
 * @description
 */
@RestController
@RequestMapping("/seckillOrder")
public class SeckillOrderController {
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedisService redisService;
    @PostMapping("/saveSeckillOrder")
    public AjaxResult saveSeckillOrder(@RequestBody Map<String,Object> map){
//        基于安全获取登陆人信息
        try{
//            String userId = SecurityContextHolder.getContext().getAuthentication().getName();
//            if(userId.equals("anonymousUser")){
//                return  new AjaxResult(401,"请下登录，再下单");
//            }
//            seckillService.saveSeckillOrder(id,userId);
            List<Map<String,Object>> goods = (List<Map<String,Object>>) map.get("list");
            Integer id = (Integer) map.get("specificationId");
//            库存充足则进行秒杀
            Long stock = redisService.getCacheObject("list:" + id.toString());
            if(stock>0) {
//                创建订单

                String res = seckillService.saveSeckillOrder(map, goods);
                return res.length() >0 ? AjaxResult.success(res): AjaxResult.error();
            }else{
                return new AjaxResult(400,"秒杀下单失败");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new AjaxResult(400,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(400,"秒杀下单失败");
        }
    }
}
